package com.es.www.kyl.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.es.www.kyl.bean.req.client.DoExerciseBaseReq;
import com.es.www.kyl.bean.res.client.QuestionInfoVO;
import com.es.www.kyl.constant.BaseConstants;
import com.es.www.kyl.domain.Question;
import com.es.www.kyl.domain.UserAnswerLog;
import com.es.www.kyl.util.UserContextHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Estranger
 * @date 2025/8/25
 * description
 */
@Component
public class WrongRoundManager extends AbstractRoundManager{
	@Override
	List<Integer> getinitialQuestionIdList(Integer categoryId, String commonRoundId, String roundId) {
		return userAnswerLogMapper.selectList(new LambdaQueryWrapper<UserAnswerLog>()
				.eq(UserAnswerLog::getUserId, UserContextHolder.getUserId())
				.eq(UserAnswerLog::getCategoryId, categoryId)
				.eq(UserAnswerLog::getRoundId, commonRoundId)
				.eq(UserAnswerLog::getCorrectFlag, 0)
		).stream().map(UserAnswerLog::getQuestionId).distinct().collect(Collectors.toList());
	}

	@Override
	public QuestionInfoVO continueRound(DoExerciseBaseReq req, BaseConstants.UserPracticeType practiceType) {
		//根据错题roundId查询出所有练习错题的记录
		UserAnswerLog lastWrongLog = userAnswerLogMapper.selectOne(new LambdaQueryWrapper<UserAnswerLog>()
				.eq(UserAnswerLog::getUserId, UserContextHolder.getUserId())
				.eq(UserAnswerLog::getCategoryId, req.getCategoryId())
				.eq(UserAnswerLog::getRoundId, req.getCorrectionRoundId())
				.eq(UserAnswerLog::getCorrectFlag, 0)
				.orderByDesc(UserAnswerLog::getQuestionId)
				.last("limit 1")
		);
		//查询出所有错题
		List<UserAnswerLog> wrongList = userAnswerLogMapper.selectList(new LambdaQueryWrapper<UserAnswerLog>()
				.eq(UserAnswerLog::getUserId, UserContextHolder.getUserId())
				.eq(UserAnswerLog::getCategoryId, req.getCategoryId())
				.eq(UserAnswerLog::getRoundId, req.getCommonRoundId())
				.eq(UserAnswerLog::getCorrectFlag, 0)
				.orderByDesc(UserAnswerLog::getQuestionId)
		);
		List<Integer> remainingWrongIdList;
		//为空表示还没开始做错题
		if (Objects.isNull(lastWrongLog)) {
			remainingWrongIdList = wrongList.stream().map(UserAnswerLog::getQuestionId).collect(Collectors.toList());
		} else {
			remainingWrongIdList = wrongList.stream().map(UserAnswerLog::getQuestionId).filter(questionId -> questionId > lastWrongLog.getQuestionId()).collect(Collectors.toList());
		}
		return QuestionInfoVO.builder()
				.roundId(req.getCorrectionRoundId())
				.questionIds(remainingWrongIdList)
				.questionDetailInfo(CollectionUtils.isNotEmpty(remainingWrongIdList) ? exerciseHelper.getQuestionDetail(remainingWrongIdList.get(0)) : null)
				.build();
	}
}
